package com.jbp.job;

import com.jbp.model.NoteMessage;
import com.jbp.service.NoteMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

/**创建ip白名单,开服执行一次就行*/
//@Component
//@Configuration
public class CreateIpList {
    @Autowired
    private RedisTemplate redisTemplate;
    public static final String keyIps="whiteips:";
    @Autowired
    private NoteMessageService noteMessageService;

//    @Scheduled(fixedDelay = 1000*60*60*60)
    public void refreshData(){
        try {
            HashSet<String> ips = new HashSet<>();
            BufferedReader reader = new BufferedReader(new FileReader("ips.txt"));
            String str;
            int i=0;
            while ((str = reader.readLine()) != null) {
                i++;
                str = str.substring(0, str.lastIndexOf("."));
                str = str.substring(0, str.lastIndexOf("."));
                ips.add(str);
                System.out.println(i+": "+str);
            }
            SetOperations setOperations = redisTemplate.opsForSet();
            setOperations.add(keyIps, ips.toArray());
            System.out.println(setOperations.size(keyIps));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    @Scheduled(fixedDelay = 1000*60*60*60)
    public void checkIps(){
        SetOperations setOperations = redisTemplate.opsForSet();
        List<NoteMessage> list = noteMessageService.list();
        for (int i = 0; i < list.size(); i++) {
            NoteMessage msg = list.get(i);
            String ip = msg.getIp();
            String str = ip;
            if (ip.contains(".")){
                str = str.substring(0, str.lastIndexOf("."));
                str = str.substring(0, str.lastIndexOf("."));
                if (setOperations.isMember(keyIps, str)) {
                    System.out.println(ip);
                }
            }
        }
    }

    public static void main(String[] args) {
        try {
            HashSet<String> ips = new HashSet<>();
            BufferedReader reader = new BufferedReader(new FileReader("ips.txt"));
            String str;
            int i=0;
            while ((str = reader.readLine()) != null) {
                i++;
                str = str.substring(0, str.lastIndexOf("."));
                str = str.substring(0, str.lastIndexOf("."));
                ips.add(str);
            }
            System.out.println(Arrays.toString(ips.toArray()));
            System.out.println(ips.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

